﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;

namespace Amitabha
{
    /// <summary>
    /// 静态的扩展类
    /// </summary>
    public static class AmitabhaExtensions
    {
        /// <summary>
        /// 使用扩展方法,添加中间件到管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options">参数对象</param>
        /// <returns></returns>
        public static IApplicationBuilder UseAmitabha(this IApplicationBuilder app, AmitabhaOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<AmitabhaMiddleware>(Options.Create(options));
        }

        /// <summary>
        /// 使用扩展方法,添加中间件到管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="path">路径对象</param>
        /// <returns></returns>
        public static IApplicationBuilder UseAmitabha(this IApplicationBuilder app, PathString path)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return app.UseAmitabha(new AmitabhaOptions
            {
                Path = path
            });
        }

        /// <summary>
        /// 使用扩展方法,添加中间件到管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="path">路径字符串</param>
        /// <returns></returns>
        public static IApplicationBuilder UseAmitabha(this IApplicationBuilder app, string path)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return app.UseAmitabha(new AmitabhaOptions
            {
                Path = new PathString(path)
            });
        }

        /// <summary>
        /// 扩展方法,无额外参数
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseAmitabha(this IApplicationBuilder app)
        {
            // app = app ?? throw new ArgumentNullException(nameof(app));
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return app.UseMiddleware<AmitabhaMiddleware>();
        }
    }
}
